package com.css.fxfzypg.modules.preassesstaskmanage.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.css.fxfzypg.base.response.RestResponse;
import com.css.fxfzypg.constants.FxfzConstants;
import com.css.fxfzypg.modules.group.entity.GroupEntity;
import com.css.fxfzypg.modules.group.entity.GroupUserEntity;
import com.css.fxfzypg.modules.group.entity.UserEntity;
import com.css.fxfzypg.modules.group.repository.GroupRepository;
import com.css.fxfzypg.modules.group.service.GroupUserService;
import com.css.fxfzypg.modules.maps.service.SetEarthquakeMapService;
import com.css.fxfzypg.modules.message.repository.entity.MessageEntity;
import com.css.fxfzypg.modules.message.service.MessageService;
import com.css.fxfzypg.modules.preassesstaskmanage.entity.PreAssessTaskEntity;
import com.css.fxfzypg.modules.preassesstaskmanage.repository.PreAssessTaskRepository;
import com.css.fxfzypg.modules.preassesstaskmanage.service.PreAssessTaskService;
import com.css.fxfzypg.modules.preassesstaskmanage.vo.PreAssessTaskGroupVo;
import com.css.fxfzypg.modules.preassesstaskmanage.vo.PreAssessTaskVo;
import com.css.fxfzypg.modules.preassesstaskmanage.vo.PreAssessVo;
import com.css.fxfzypg.modules.spatialData.repository.entity.BoundaryEntity;
import com.css.fxfzypg.modules.spatialData.service.BoundaryService;
import com.css.fxfzypg.modules.surveytaskmanage.vo.TaskVo;
import com.css.fxfzypg.util.CreateGson;
import com.css.fxfzypg.util.PlatformObjectUtils;
import com.css.fxfzypg.util.UUIDGenerator;
import com.css.fxfzypg.web.PlatformSessionContext;
import com.css.fxfzypg.zcpt.sys.entity.SUser;
import com.css.fxfzypg.zcpt.sys.service.SysAreaService;
import com.css.fxfzypg.zcpt.sys.service.SysRoleService;
import com.css.fxfzypg.zcpt.sys.service.impl.SUserServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author
 * @program
 * @description
 * @create 2022/8/8 10:42
 **/
@Service
@Slf4j
public class PreAssessTaskServiceImpl implements PreAssessTaskService {
    @Autowired
    PreAssessTaskRepository preAssessTaskRepository;

    @Autowired
    SUserServiceImpl sUserServiceImpl;

    @Autowired
    GroupUserService groupUserService;

    @Autowired
    SysAreaService sysAreaService;

    @Autowired
    GroupRepository groupRepository;

    @Autowired
    MessageService messageService;

    @Autowired
    BoundaryService boundaryService;

    @Resource
    SetEarthquakeMapService setEarthquakeMapService;//地图使用

    @Autowired
    SysRoleService sysRoleService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String saveTask(PreAssessTaskVo preAssessTaskVo) {
        PreAssessTaskEntity parentTask = preAssessTaskVo.getParentTask();
        String userId = PlatformSessionContext.getUserID();
        String parentTaskId = UUIDGenerator.getUUID();
        StringBuilder taskRegion = new StringBuilder("");
        StringBuilder subTaskRegion = new StringBuilder("");
        parentTask.setDelFlag("0");
        parentTask.setCreateUser(userId);
        parentTask.setCreateTime(new Date());
        //获取用户名称
        String sUser = sUserServiceImpl.getSUser(userId);
        SUser userInfo = CreateGson.createGson().fromJson(sUser, SUser.class);
        String userName = userInfo.getUserName();
        parentTask.setTaskManager(userName);
        parentTask.setTaskManagerId(userId);
        parentTask.setId(parentTaskId);
        parentTask.setParentId("0");

        //如果任务区域是区划选择的，通过传入的divisoncode查询任务区域
        if (!PlatformObjectUtils.isEmpty(parentTask.getRegionCodes())) {
            String regionCodes = parentTask.getRegionCodes();
            String[] split = regionCodes.split(",");
            List<String> regionCodeList = Arrays.asList(split);
            for (String regionCode : regionCodeList) {
                BoundaryEntity boundaryEntityByCode = boundaryService.getBoundaryEntityByCode(regionCode);
                taskRegion.append(boundaryEntityByCode.getCoordinate() + ";");
            }
            parentTask.setTaskRegion(taskRegion.substring(0, taskRegion.lastIndexOf(";")));
        }
        //获取任务区域的空间数据
        parentTask.setGeom(setEarthquakeMapService.getGeomByTaskRegion(parentTask.getTaskRegion()));

        StringBuilder str = new StringBuilder();
        List<String> districtList = parentTask.getParentdistrictList();
        for (String districts : districtList) {
            str.append(districts + "、");
        }
        String district = str.substring(0, str.lastIndexOf("、"));
        parentTask.setTaskDistrict(district);
        if (PlatformObjectUtils.isEmpty(parentTask.getGroupId())) {
            parentTask.setTaskStatus("0");
        } else {
            parentTask.setTaskStatus("1");
            String sUser1 = sUserServiceImpl.getSUser(parentTask.getGroupLeaderId());
            SUser user = CreateGson.createGson().fromJson(sUser1, SUser.class);
            if (user != null && PlatformObjectUtils.isNotEmpty(user.getMobilePhone())) {
                parentTask.setMobilePhone(user.getMobilePhone());
            }

            List<String> list = new ArrayList<>();
            GroupEntity groupEntity = groupRepository.selectGroup(parentTask.getGroupId());
            list.add(groupEntity.getGroupLeaderId());
            List<GroupUserEntity> groupUserEntities = groupUserService.selectGroupMemberAndGroupExpert(parentTask.getGroupId());
            for (GroupUserEntity groupUserEntitie : groupUserEntities) {
                list.add(groupUserEntitie.getUserId());
            }
            for (String id : list) {
                MessageEntity messageEntity = new MessageEntity();
                messageEntity.setMessageGenerator(userId);
                messageEntity.setMessageReceiver(id);
                messageEntity.setMessageContent(userName + "给您分配了 " + parentTask.getTaskName() + " 任务");
                messageService.addMessage(messageEntity);
            }
        }

        PreAssessTaskEntity subTask = preAssessTaskVo.getSubTask();
        if (!PlatformObjectUtils.isEmpty(subTask)) {
            //如果任务区域是区划选择的，通过传入的divisoncode查询任务区域
            if (!PlatformObjectUtils.isEmpty(subTask.getRegionCodes())) {
                String regionCodes = subTask.getRegionCodes();
                String[] split = regionCodes.split(",");
                List<String> regionCodeList = Arrays.asList(split);
                for (String regionCode : regionCodeList) {
                    BoundaryEntity boundaryEntityByCode = boundaryService.getBoundaryEntityByCode(regionCode);
                    subTaskRegion.append(boundaryEntityByCode.getCoordinate() + ";");
                }
                subTask.setTaskRegion(subTaskRegion.substring(0, subTaskRegion.lastIndexOf(";")));
            }
            //获取任务区域的空间数据
            subTask.setGeom(setEarthquakeMapService.getGeomByTaskRegion(subTask.getTaskRegion()));

            StringBuilder str1 = new StringBuilder();
            List<String> subTaskdistricts = subTask.getSubdistrictList();

            for (String subTaskdistrict : subTaskdistricts) {
                for (String districts : districtList) {
                    if (districts.contains(subTaskdistrict)) {
                        str1.append(districts + "、");
                    }
                }
            }
            String subDistrict = str1.substring(0, str1.lastIndexOf("、"));
            subTask.setTaskDistrict(subDistrict);

            subTask.setDelFlag("0");
            subTask.setCreateUser(userId);
            subTask.setCreateTime(new Date());
            //获取用户名称
            subTask.setTaskManager(userName);
            subTask.setTaskManagerId(userId);
            subTask.setId(UUIDGenerator.getUUID());
            subTask.setParentId(parentTaskId);
            subTask.setParentTask(parentTask.getTaskNum());
            if (PlatformObjectUtils.isEmpty(subTask.getGroupId())) {
                subTask.setTaskStatus("0");
            } else {
                parentTask.setTaskStatus("1");
                subTask.setTaskStatus("1");
                String sUser1 = sUserServiceImpl.getSUser(subTask.getGroupLeaderId());
                SUser user = CreateGson.createGson().fromJson(sUser1, SUser.class);
                if (PlatformObjectUtils.isNotEmpty(user.getMobilePhone())) {
                    subTask.setMobilePhone(user.getMobilePhone());
                }

                List<String> list = new ArrayList<>();
                GroupEntity groupEntity = groupRepository.selectGroup(subTask.getGroupId());
                list.add(groupEntity.getGroupLeaderId());
                List<GroupUserEntity> groupUserEntities = groupUserService.selectGroupMemberAndGroupExpert(subTask.getGroupId());
                for (GroupUserEntity groupUserEntitie : groupUserEntities) {
                    list.add(groupUserEntitie.getUserId());
                }
                for (String id : list) {
                    MessageEntity messageEntity = new MessageEntity();
                    messageEntity.setMessageGenerator(userId);
                    messageEntity.setMessageReceiver(id);
                    messageEntity.setMessageContent(userName + "给您分配了 " + subTask.getTaskName() + " 任务");
                    messageService.addMessage(messageEntity);
                }
            }
            preAssessTaskRepository.saveTask(subTask);
        }
        preAssessTaskRepository.saveTask(parentTask);

        return parentTaskId;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveSubTask(PreAssessTaskEntity subTask) {
        PreAssessTaskEntity parentTask = preAssessTaskRepository.findById(subTask.getParentId());
        StringBuilder subTaskRegion = new StringBuilder("");
        String userID = PlatformSessionContext.getUserID();
        if (!PlatformObjectUtils.isEmpty(subTask)) {
            subTask.setDelFlag("0");
            subTask.setCreateUser(userID);
            subTask.setCreateTime(new Date());
            //获取用户名称
            String sUser = sUserServiceImpl.getSUser(PlatformSessionContext.getUserID());
            SUser userInfo = CreateGson.createGson().fromJson(sUser, SUser.class);
            String userName = userInfo.getUserName();
            subTask.setTaskManager(userName);
            subTask.setId(UUIDGenerator.getUUID());
            subTask.setTaskManagerId(parentTask.getTaskManagerId());
            //如果任务区域是区划选择的，通过传入的divisoncode查询任务区域
            if (!PlatformObjectUtils.isEmpty(subTask.getRegionCodes())) {
                String regionCodes = subTask.getRegionCodes();
                String[] split = regionCodes.split(",");
                List<String> regionCodeList = Arrays.asList(split);
                for (String regionCode : regionCodeList) {
                    BoundaryEntity boundaryEntityByCode = boundaryService.getBoundaryEntityByCode(regionCode);
                    subTaskRegion.append(boundaryEntityByCode.getCoordinate() + ";");
                }
                subTask.setTaskRegion(subTaskRegion.substring(0, subTaskRegion.lastIndexOf(";")));
            }
            //获取任务区域的空间数据
            subTask.setGeom(setEarthquakeMapService.getGeomByTaskRegion(subTask.getTaskRegion()));


            StringBuilder str1 = new StringBuilder();
            List<String> districtList = subTask.getParentdistrictList();
            List<String> subTaskdistricts = subTask.getSubdistrictList();

            for (String subTaskdistrict : subTaskdistricts) {
                for (String districts : districtList) {
                    if (districts.contains(subTaskdistrict)) {
                        str1.append(districts + "、");
                    }
                }
            }
            String subDistrict = str1.substring(0, str1.lastIndexOf("、"));
            subTask.setTaskDistrict(subDistrict);

            if (PlatformObjectUtils.isEmpty(subTask.getGroupId())) {
                subTask.setTaskStatus("0");
            } else {
                preAssessTaskRepository.completeTask("1", subTask.getParentId());
                subTask.setTaskStatus("1");
                String sUser1 = sUserServiceImpl.getSUser(subTask.getGroupLeaderId());
                SUser user = CreateGson.createGson().fromJson(sUser1, SUser.class);
                if (PlatformObjectUtils.isNotEmpty(user.getMobilePhone())) {
                    subTask.setMobilePhone(user.getMobilePhone());
                }

                List<String> list = new ArrayList<>();
                GroupEntity groupEntity = groupRepository.selectGroup(subTask.getGroupId());
                list.add(groupEntity.getGroupLeaderId());
                List<GroupUserEntity> groupUserEntities = groupUserService.selectGroupMemberAndGroupExpert(subTask.getGroupId());
                for (GroupUserEntity groupUserEntitie : groupUserEntities) {
                    list.add(groupUserEntitie.getUserId());
                }
                for (String id : list) {
                    MessageEntity messageEntity = new MessageEntity();
                    messageEntity.setMessageGenerator(userID);
                    messageEntity.setMessageReceiver(id);
                    messageEntity.setMessageContent(userName + "给您分配了 " + subTask.getTaskName() + " 任务");
                    messageService.addMessage(messageEntity);
                }
            }
            preAssessTaskRepository.saveTask(subTask);
        }
    }

    @Override
    public Map<String, Object> getPage(TaskVo taskVo, int curPage, int pageSize) {
        taskVo.setCreateUser(PlatformSessionContext.getUserID());
        Map<String, Object> parentTask = preAssessTaskRepository.findParentIdByTask("0", taskVo, curPage, pageSize);
        List<PreAssessVo> tasks = (List<PreAssessVo>) parentTask.get("rows");
        String provinceListStr = sysAreaService.jsonSAreaTree("1");
        JSONArray dataJSONArr = JSONObject.parseArray(provinceListStr);
        Map<String, String> areaMap = new HashMap<>();
        for (Object o : dataJSONArr) {
            areaMap.put(JSONObject.parseObject(JSONObject.toJSONString(o)).getString("name"), JSONObject.parseObject(JSONObject.toJSONString(o)).getString("id"));
        }
        for (PreAssessVo task : tasks) {
            List<PreAssessVo> subTasks = getSubTaskList(task.getId(), taskVo);
            task.setChildren(subTasks);
            String taskDistrict = task.getTaskDistrict();
            Set<String> provSet = new HashSet<>();
            String[] allAreaArr = taskDistrict.split("、");
            for (String area : allAreaArr) {
                provSet.add(area.split("-")[0]);
            }
            for (String prov : provSet) {
                task.getProvinceIdList().add(areaMap.get(prov));
            }
            task.setProvinceNames(StringUtils.join(provSet, "、"));
        }
        return parentTask;
    }

    private List<PreAssessVo> getSubTaskList(String id, TaskVo taskVo) {
        taskVo = new TaskVo();
        List<PreAssessVo> tasks = preAssessTaskRepository.findSubIdByTask(id, taskVo);
        if (tasks != null) {
            for (PreAssessVo task : tasks) {
                String id1 = task.getId();
                List<PreAssessVo> subTask = preAssessTaskRepository.findSubIdByTask(id1, taskVo);
                task.setChildren(subTask);
            }
        }
        return tasks;
    }

    private List<PreAssessVo> getSubTasks(String id, TaskVo taskVo) {
        List<PreAssessVo> tasks = preAssessTaskRepository.findSubIdByTask(id, taskVo);
        if (tasks != null) {
            for (PreAssessVo task : tasks) {
                String id1 = task.getId();
                List<PreAssessVo> subTask = preAssessTaskRepository.findSubIdByTask(id1, taskVo);
                task.setChildren(subTask);
            }
        }
        return tasks;
    }

    @Override
    public List<PreAssessTaskEntity> getSubTask(String parentTaskId) {
        List<PreAssessTaskEntity> subTaskList = new ArrayList<>();
        if (!PlatformObjectUtils.isEmpty(parentTaskId)) {
            subTaskList = preAssessTaskRepository.getSubTask(parentTaskId);
            return subTaskList;
        }
        return subTaskList;
    }

    @Override
    public PreAssessTaskGroupVo findById(String taskId) {
        PreAssessTaskGroupVo preAssessTaskGroupVo = new PreAssessTaskGroupVo();
        PreAssessTaskEntity preAssessTaskEntity = preAssessTaskRepository.findById(taskId);
        preAssessTaskGroupVo.setPreAssessTaskEntity(preAssessTaskEntity);

        List<UserEntity> memberList = new ArrayList<>();
        List<UserEntity> expertList = new ArrayList<>();

        List<GroupUserEntity> groupUserEntityList = groupUserService.selectGroupMemberAndGroupExpert(preAssessTaskEntity.getGroupId());

        for (GroupUserEntity groupUserEntity : groupUserEntityList) {
            String groupUserInfo = sUserServiceImpl.getGroupUserInfo(groupUserEntity.getUserId());
            UserEntity userInfo = CreateGson.createGson().fromJson(groupUserInfo, UserEntity.class);
            if ("0".equals(groupUserEntity.getRole())) {
                memberList.add(userInfo);
            } else {
                expertList.add(userInfo);
            }
        }
        preAssessTaskGroupVo.setMemberlist(memberList);
        preAssessTaskGroupVo.setExpertlist(expertList);
        return preAssessTaskGroupVo;
    }

    @Override
    public PreAssessTaskEntity getById(String taskId) {
        return preAssessTaskRepository.findById(taskId);
    }

    @Override
    public void updateTask(PreAssessTaskEntity preAssessTaskEntity) {
        List<String> list = new ArrayList<>();
        String groupId = preAssessTaskEntity.getGroupId();
        preAssessTaskEntity.setUpdateTime(new Date());
        preAssessTaskEntity.setUpdateUser(PlatformSessionContext.getUserID());
        if (!PlatformObjectUtils.isEmpty(preAssessTaskEntity.getGroupId())) {
            String sUser1 = sUserServiceImpl.getSUser(preAssessTaskEntity.getGroupLeaderId());
            SUser user = CreateGson.createGson().fromJson(sUser1, SUser.class);
            if (user != null && PlatformObjectUtils.isNotEmpty(user.getMobilePhone())) {
                preAssessTaskEntity.setMobilePhone(user.getMobilePhone());
            }
            preAssessTaskEntity.setTaskStatus("1");
            if (!"0".equals(preAssessTaskEntity.getParentId())) {
                preAssessTaskRepository.completeTask("1", preAssessTaskEntity.getParentId());
            }
        }
        preAssessTaskRepository.updateTask(preAssessTaskEntity);

        if (!PlatformObjectUtils.isEmpty(groupId)) {
            GroupEntity groupEntity = groupRepository.selectGroup(groupId);
            list.add(groupEntity.getGroupLeaderId());
            List<GroupUserEntity> groupUserEntities = groupUserService.selectGroupMemberAndGroupExpert(groupId);
            for (GroupUserEntity groupUserEntitie : groupUserEntities) {
                list.add(groupUserEntitie.getUserId());
            }
            for (String id : list) {
                MessageEntity messageEntity = new MessageEntity();
                messageEntity.setMessageGenerator(preAssessTaskEntity.getCreateUser());
                messageEntity.setMessageReceiver(id);
                String sUser = sUserServiceImpl.getSUser(preAssessTaskEntity.getCreateUser());
                SUser userInfo = CreateGson.createGson().fromJson(sUser, SUser.class);
                messageEntity.setMessageContent(userInfo.getUserName() + "给您分配了 " + preAssessTaskEntity.getTaskName() + " 任务");
                messageService.addMessage(messageEntity);
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void assignGroup(PreAssessTaskEntity preAssessTaskEntity) {
        List<String> list = new ArrayList<>();
        String groupId = preAssessTaskEntity.getGroupId();
        preAssessTaskEntity.setUpdateUser(PlatformSessionContext.getUserID());
        preAssessTaskEntity.setUpdateTime(new Date());
        if (!PlatformObjectUtils.isEmpty(preAssessTaskEntity.getGroupId())) {
            String sUser1 = sUserServiceImpl.getSUser(preAssessTaskEntity.getGroupLeaderId());
            SUser user = CreateGson.createGson().fromJson(sUser1, SUser.class);
            if (PlatformObjectUtils.isNotEmpty(user.getMobilePhone())) {
                preAssessTaskEntity.setMobilePhone(user.getMobilePhone());
            }
            preAssessTaskEntity.setTaskStatus("1");
            if (!"0".equals(preAssessTaskEntity.getParentId())) {
                preAssessTaskRepository.completeTask("1", preAssessTaskEntity.getParentId());
            }
        }
        preAssessTaskRepository.assignGroup(preAssessTaskEntity);

        GroupEntity groupEntity = groupRepository.selectGroup(groupId);
        list.add(groupEntity.getGroupLeaderId());
        List<GroupUserEntity> groupUserEntities = groupUserService.selectGroupMemberAndGroupExpert(groupId);
        for (GroupUserEntity groupUserEntitie : groupUserEntities) {
            list.add(groupUserEntitie.getUserId());
        }
        for (String id : list) {
            MessageEntity messageEntity = new MessageEntity();
            messageEntity.setMessageGenerator(preAssessTaskEntity.getCreateUser());
            messageEntity.setMessageReceiver(id);
            String sUser = sUserServiceImpl.getSUser(preAssessTaskEntity.getCreateUser());
            SUser userInfo = CreateGson.createGson().fromJson(sUser, SUser.class);
            messageEntity.setMessageContent(userInfo.getUserName() + "给您分配了 " + preAssessTaskEntity.getTaskName() + " 任务");
            messageService.addMessage(messageEntity);
        }
    }

    @Override
    public String getSubTaskCode(String parentTaskNum) {
        StringBuilder stringBuilder = new StringBuilder(parentTaskNum + "-");
        String subNum = "";
        DecimalFormat decimalFormat = new DecimalFormat("000");
        PreAssessTaskEntity parentTask = preAssessTaskRepository.getParentTask(parentTaskNum);
        if (!PlatformObjectUtils.isEmpty(parentTask)) {
            List<PreAssessTaskEntity> subTask = preAssessTaskRepository.getSubTask(parentTask.getId());
            if (!PlatformObjectUtils.isEmpty(subTask)) {
                String maxSubTaskCNum = preAssessTaskRepository.getMaxSubTaskCNum(parentTaskNum);
                String str = maxSubTaskCNum.substring(11, maxSubTaskCNum.length());
                int i = Integer.parseInt(str) + 1;
                subNum = decimalFormat.format(i);
            } else {
                int i = 1;
                subNum = decimalFormat.format(i);
            }
        } else {
            int i = 1;
            subNum = decimalFormat.format(i);
        }
        return stringBuilder.append(subNum).toString();
    }

    @Override
    public String getTaskCode(String taskYear) {
        DecimalFormat decimalFormat = new DecimalFormat("000");
        String parentNum = "";
        String userId = PlatformSessionContext.getUserID();
        StringBuilder str = new StringBuilder("");
        String role = sysRoleService.getRoleByUserId(userId);
        List<Map> roleMaps = JSONObject.parseArray(role, Map.class);
        for (Map roleMap : roleMaps) {
            str.append(roleMap.get("roleCode") + ",");
        }
        String roles = str.toString();

        String divisionCode = sysAreaService.getAreaCodeByUserId(userId);
        StringBuilder code = new StringBuilder("");

        StringBuilder stringBuilder = new StringBuilder("P");
        if (PlatformObjectUtils.isEmpty(taskYear)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
            taskYear = sdf.format(new Date());
            stringBuilder.append(taskYear);
        } else {
            stringBuilder.append(taskYear);
        }
        divisionCode = divisionCode.substring(0, 2);
        if (roles.contains(FxfzConstants.YPG_COUN_YW_ROLE) || roles.contains(FxfzConstants.YPG_COUN_GL_ROLE)) {
            stringBuilder.append("00");
            code.append("00");
        } else {
            stringBuilder.append(divisionCode);
            code.append(divisionCode);
        }

        String maxParentNum = preAssessTaskRepository.getMaxParentNum(taskYear, code.toString());
        if (PlatformObjectUtils.isEmpty(maxParentNum)) {
            int i = 1;
            parentNum = decimalFormat.format(i);
        } else {
            String substring = maxParentNum.substring(7);
            parentNum = decimalFormat.format(Integer.parseInt(substring) + 1);
        }
        return stringBuilder.append(parentNum).toString();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteTask(List<String> list) {
        for (String id : list) {
            PreAssessTaskEntity preAssessTaskEntity = preAssessTaskRepository.findById(id);
            if ("0".equals(preAssessTaskEntity.getParentId())) {
                List<PreAssessTaskEntity> subTaskList = preAssessTaskRepository.getSubTask(preAssessTaskEntity.getId());
                if (!PlatformObjectUtils.isEmpty(subTaskList)) {
                    for (PreAssessTaskEntity subTask : subTaskList) {
                        preAssessTaskRepository.deleteTask("1", subTask.getId());
                    }
                }
            }
            preAssessTaskRepository.deleteTask("1", preAssessTaskEntity.getId());
        }
    }

    @Override
    public List<PreAssessTaskEntity> getParentTask() {
        String userId = PlatformSessionContext.getUserID();
        List<PreAssessTaskEntity> parentTask = preAssessTaskRepository.getAllparentTask("0", userId);
        return parentTask;
    }

    @Override
    public PreAssessTaskEntity getPreAssessTaskByTaskNum(String taskNum) {
        return preAssessTaskRepository.getPreAssessTaskByTaskNum(taskNum);
    }

    @Override
    public boolean updateTaskStatus(String taskStatus, String reportId) {
        return preAssessTaskRepository.updateTaskStatus(taskStatus, reportId);
    }

    @Override
    public void completeTask(String taskId) {
        List<String> list = new ArrayList<>();
        List<String> subList = new ArrayList<>();
        String taskStatus = "3";
        PreAssessTaskEntity task = preAssessTaskRepository.findById(taskId);
        if ("0".equals(task.getParentId())) {
            preAssessTaskRepository.completeTask(taskStatus, taskId);
            //判断是否是有子任务的父任务
            if (!PlatformObjectUtils.isEmpty(task.getGroupId())) {
                GroupEntity groupEntity = groupRepository.selectGroup(task.getGroupId());
                list.add(groupEntity.getGroupLeaderId());
                List<GroupUserEntity> groupUserEntities = groupUserService.selectGroupMemberAndGroupExpert(task.getGroupId());
                for (GroupUserEntity groupUserEntitie : groupUserEntities) {
                    if ("0".equals(groupUserEntitie.getRole())) {
                        list.add(groupUserEntitie.getUserId());
                    }
                }
                for (String item : list) {
                    MessageEntity messageEntity = new MessageEntity();
                    messageEntity.setMessageGenerator(task.getCreateUser());
                    messageEntity.setMessageReceiver(item);
                    String sUser = sUserServiceImpl.getSUser(task.getCreateUser());
                    SUser userInfo = CreateGson.createGson().fromJson(sUser, SUser.class);
                    String userName = task.getCreateUser();
                    if (userInfo != null) {
                        userName = userInfo.getUserName();
                    }
                    messageEntity.setMessageContent(userName + "结束了 " + task.getTaskName() + " 任务");
                    messageService.addMessage(messageEntity);
                }
            } else {
                List<PreAssessTaskEntity> subTasks = preAssessTaskRepository.getSubTask(task.getId());
                for (PreAssessTaskEntity subTask : subTasks) {
                    preAssessTaskRepository.completeTask(taskStatus, subTask.getId());
                    GroupEntity subGroupEntity = groupRepository.selectGroup(subTask.getGroupId());
                    subList.add(subGroupEntity.getGroupLeaderId());
                    List<GroupUserEntity> subGroupUserEntities = groupUserService.selectGroupMemberAndGroupExpert(subTask.getGroupId());
                    for (GroupUserEntity groupUserEntitie : subGroupUserEntities) {
                        if ("0".equals(groupUserEntitie.getRole())) {
                            subList.add(groupUserEntitie.getUserId());
                        }
                    }
                    for (String item : subList) {
                        MessageEntity messageEntity = new MessageEntity();
                        messageEntity.setMessageGenerator(task.getCreateUser());
                        messageEntity.setMessageReceiver(item);
                        String sUser = sUserServiceImpl.getSUser(task.getCreateUser());
                        SUser userInfo = CreateGson.createGson().fromJson(sUser, SUser.class);
                        String userName = task.getCreateUser();
                        if (userInfo != null) {
                            userName = userInfo.getUserName();
                        }
                        messageEntity.setMessageContent(userName + "结束了 " + subTask.getTaskName() + " 任务");
                        messageService.addMessage(messageEntity);
                    }
                    subList.clear();
                }
            }
        } else {
            PreAssessTaskEntity parentTask = preAssessTaskRepository.findById(task.getParentId());
            preAssessTaskRepository.completeTask(taskStatus, parentTask.getId());
            List<PreAssessTaskEntity> subTasks = preAssessTaskRepository.getSubTask(parentTask.getId());
            for (PreAssessTaskEntity subTask : subTasks) {
                preAssessTaskRepository.completeTask(taskStatus, subTask.getId());
                GroupEntity subGroupEntity = groupRepository.selectGroup(subTask.getGroupId());
                subList.add(subGroupEntity.getGroupLeaderId());
                List<GroupUserEntity> subGroupUserEntities = groupUserService.selectGroupMemberAndGroupExpert(subTask.getGroupId());
                for (GroupUserEntity groupUserEntitie : subGroupUserEntities) {
                    if ("0".equals(groupUserEntitie.getRole())) {
                        subList.add(groupUserEntitie.getUserId());
                    }
                }
                for (String item : subList) {
                    MessageEntity messageEntity = new MessageEntity();
                    messageEntity.setMessageGenerator(task.getCreateUser());
                    messageEntity.setMessageReceiver(item);
                    String sUser = sUserServiceImpl.getSUser(task.getCreateUser());
                    SUser userInfo = CreateGson.createGson().fromJson(sUser, SUser.class);
                    messageEntity.setMessageContent(userInfo.getUserName() + "结束了 " + subTask.getTaskName() + " 任务");
                    messageService.addMessage(messageEntity);
                }
                subList.clear();
            }
        }
    }

    @Override
    public RestResponse getCityIdByName(String taskDistrict) {
        HashMap<String, String> map = new HashMap<>();
        try {
            String[] split = taskDistrict.split("、");
            for (String s : split) {
                if (s.lastIndexOf("-") != -1) {
                    String substring = s.substring(0, s.indexOf("-"));
                    String provinceId = sysAreaService.getIdByCondition(URLEncoder.encode(substring, "utf-8"),
                            URLEncoder.encode("", "utf-8"),
                            URLEncoder.encode("", "utf-8"));
                    map.put(substring, provinceId);
                } else {
                    String provinceId = sysAreaService.getIdByCondition(URLEncoder.encode(s, "utf-8"),
                            URLEncoder.encode("", "utf-8"),
                            URLEncoder.encode("", "utf-8"));
                    map.put(s, provinceId);
                }
            }
        } catch (Exception e) {
            String errormessage = "查询失败";
            log.error(errormessage, e);
            return RestResponse.fail(errormessage);
        }
        return RestResponse.succeed(map);
    }

    @Override
    public RestResponse saveSurveySamplingPoint(String samplingSurveyPointId, String id) {
        try {
            preAssessTaskRepository.saveSurveySamplingPoint(samplingSurveyPointId, id);
            return RestResponse.succeed("关联成功!");
        } catch (Exception e) {
            String errorMassage = "关联失败!";
            log.error(errorMassage, e);
            return RestResponse.fail(errorMassage);
        }
    }
}
